import { CustomerServiceSvr } from './../../services/customerServiceSvr';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';

import { Component, forwardRef, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms';
import { Login } from 'src/app/service/login.service';
import { CommonServiceSvr } from 'src/app/service/common.service';
import { Verify } from 'src/app/service/verify.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less']
})



export class LoginComponent implements OnInit {


  constructor(
    private fb: FormBuilder,
    private login: Login,
    private message: NzMessageService,
    private router: Router,
    private common: CommonServiceSvr,
    private customerServiceSvr: CustomerServiceSvr,
    private verify: Verify
  ) {}



  validateForm!: FormGroup;
  updatePwdModal: boolean = false
  phone: string = ''
  code: string = ''
  newPwd: string = ''
  newPwdConfire: string = ''


  async submitForm(): Promise<void> {
    if (this.validateForm.valid) {
      console.log(this.validateForm.valid)
      try {
        let res = await this.login.Login(this.validateForm.value.userName, this.validateForm.value.password, '')
        if(res.Code!==-22) {
          // console.log(res)
          this.message.success('登录成功')
          localStorage.setItem('Token', JSON.stringify(res.Token))
          localStorage.setItem('customerId', JSON.stringify(res.UserId))
          localStorage.setItem('customerNickName', JSON.stringify(res.NickName))
          this.router.navigate(['/home'])
        } else {
          this.message.error(`${res.Msg}`)
        }
      } catch (error) {
        this.message.error('登陆失败，请重新登录')
        console.log(error)
      }
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }


  ngOnInit(): void {
    this.validateForm = this.fb.group({
      userName: [null, [Validators.required]],
      password: [null, [Validators.required]],
      remember: [true]
    });
  }


  // 取消登录
  cancel() {
    this.router.navigate(['/home'])
  }

  register(){
    this.router.navigate(['/register'])
  }

  handleCancel() {
    this.updatePwdModal = false
  }

  // 忘记密码
  handleOk() {
    if(this.verify.phone(this.phone)&&this.verify.code(this.code)&&this.verify.password(this.newPwd)&&this.verify.pwdConf(this.newPwd, this.newPwdConfire)) {
      this.updatePwdModal = false
      try {
        let res = this.customerServiceSvr.forgotPwd(this.phone, this.code, this.newPwd, this.newPwdConfire, 1, '')
        console.log(res)
        this.message.success('密码修改成功')
      } catch (error) {
        console.log(error)
      }
    } else {
      this.updatePwdModal = true
    }
  }

  handleClose() {
    this.updatePwdModal = false
  }


  codeFlag: number = 1;
  codeData: string = '';
  //  请求返回的结果
  res: String | undefined;
  // 验证码倒计时
  codeCount: number = 0;
  timer: any = null;
  showCodeBtn = true

  // 获取验证码
  async getCaptcha(): Promise<boolean> {

    if(this.verify.phone(this.phone)) {
      this.codeFlag = 1
      this.codeData = this.phone
    } else {
      return false;
    }

    const Time: number = 60
    if(this.timer !== -1) {
      this.codeCount = Time
      this.showCodeBtn = false
      this.timer = setInterval(()=>{
        if(this.codeCount>0 && this.codeCount <= Time) {
          this.codeCount--
        } else {
          this.showCodeBtn = true
          clearInterval(this.timer)
          this.timer = null
        }
      }, 1000)
    }

    const res = await this.common.sendCode(this.phone, this.codeFlag)
    if(res !== undefined) {
      this.message.error('验证码获取失败')
    }

    return true
  }
}
